package com.nanfang51g3.ckz.ui.home;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.nanfang51g3.ckz.R;
import com.nanfang51g3.ckz.application.CkzApplication;
import com.nanfang51g3.ckz.event.PostTypeData;
import com.nanfang51g3.ckz.event.RxBus;
import com.nanfang51g3.ckz.ui.fragment.home.HomeAccountingFragment;
import com.nanfang51g3.ckz.ui.fragment.home.HomeIndexFragment;
import com.nanfang51g3.ckz.ui.fragment.home.HomeMeFragment;
import com.nanfang51g3.ckz.ui.fragment.home.HomeRightFragment;
import com.nanfang51g3.ckz.ui.login.LoginActivity;
import com.nanfang51g3.ckz.utils.AppManager;
import com.nanfang51g3.ckz.utils.EasyToast;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.utils.SPUtil;
import com.nanfang51g3.ckz.utils.SystemBarTintManager;
import com.nanfang51g3.ckz.widget.progress.NumberProgressBar;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by Administrator on 2016/5/18.
 */
public class HomeMainActivity extends SlidingFragmentActivity implements HomeMainContract.View   {
    HomeMainContract.HomeMainActionsListener homeMainActionsListener;
    @Bind(R.id.btn_communication)
    Button btnCommunication;
    @Bind(R.id.btn_client_management)
    Button btnClientManagement;
    @Bind(R.id.btn_marketing_communication)
    Button btnMarketingCommunication;
    private Subscription rxSubscription;
    private HomeRightFragment homeRightFragment;
    private Button[] mTabs;
    private Fragment[] fragments;
    private int index;
    private int currentTabIndex;
    private HomeIndexFragment homeIndexFragment;
    private HomeAccountingFragment homeAccountingFragment;
    private HomeMeFragment homeMeFragment;
    private SlidingMenu slidingMenu;
    Drawable a, aa, b, bb, c, cc;
    NumberProgressBar numberProgressBar;
    ProgressBarDialog progressBarDialog;
    TextView tv_dialog_version;
    int displayWidth = 0;
    int displayHeight = 0;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);//解除绑定，官方文档只对fragment做了解绑
        if (!rxSubscription.isUnsubscribed()) {
            rxSubscription.unsubscribe();
        }
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    /**
     * 全屏幕，状态栏透明
     */
    public void initThemeColor() {
        //判断SDK版本是否大于或等于19
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(R.color.theme);//通知栏所需颜色
    }

    @Override
    public Context getContext() {
        return this;
    }


    Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    long progress = (long) msg.obj;
                    numberProgressBar.incrementProgressBy((int) (progress / 1000 % 1000));
                    break;
            }
        }
    };

    @Override
    public void updateProgress(final long numberProgress) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Message msg = new Message();
                    msg.what = 100;
                    msg.obj = numberProgress;
                    myHandler.sendMessage(msg);
                } catch (Exception e) {

                }

            }
        }).start();
    }

    @Override
    public void installationApk(File file) {
        progressBarDialog.dismiss();
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        startActivity(intent);

    }

    @Override
    public void noUpdatesVersionCode(String message) {
        EasyToast.showShort(this, message);
    }

    class CallCancelDetermineListener implements View.OnClickListener {
        String versionName;
        String apkUrl;

        CallCancelDetermineListener(final String versionName, final String apkUrl) {
            this.versionName = versionName;
            this.apkUrl = apkUrl;
        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.tv_cancel:
                    progressBarDialog.dismiss();
                    break;
                case R.id.tv_determine:
                    /**
                     * @see HomeMainPresenter#downloadApk(String, String)
                     */
                    homeMainActionsListener.downloadApk(versionName, apkUrl, numberProgressBar);
                    break;
                default:
                    break;
            }
        }
    }


    class ProgressBarDialog extends Dialog {
        CallCancelDetermineListener listener;

        public void setListener(CallCancelDetermineListener listener) {
            this.listener = listener;
        }

        public ProgressBarDialog(Context context, boolean cancelable,
                                 OnCancelListener cancelListener) {
            super(context, cancelable, cancelListener);
            // TODO Auto-generated constructor stub
        }

        public ProgressBarDialog(Context context, int theme) {
            super(context, theme);
            // TODO Auto-generated constructor stub
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            View view = getLayoutInflater().inflate(R.layout.update_app_progress_bar_dialog, null);

            numberProgressBar = (NumberProgressBar) view.findViewById(R.id.numberbar1);
            tv_dialog_version = (TextView) view.findViewById(R.id.tv_dialog_version);
            setContentView(view);
            initDialogSize();
            view.findViewById(R.id.tv_cancel).setOnClickListener(listener);
            view.findViewById(R.id.tv_determine).setOnClickListener(listener);


        }

        private void initDialogSize() {
            // TODO Auto-generated method stub
            Window dialogWindow = this.getWindow();
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            dialogWindow.setGravity(Gravity.CENTER);
            lp.width = displayWidth - 60;
            lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            dialogWindow.setAttributes(lp);
        }
    }


    @Override
    public void showDialog(final String versionName, final String apkUrl) {
        // TODO Auto-generated method stub
        progressBarDialog = new ProgressBarDialog(HomeMainActivity.this, R.style.progress_bar_style);
        progressBarDialog.setListener(new CallCancelDetermineListener(versionName, apkUrl));
        progressBarDialog.show();
        progressBarDialog.setCanceledOnTouchOutside(false);
        tv_dialog_version.setText("有最新版本：" + versionName);
    }

    private void initMetrics() {
        // TODO Auto-generated method stub
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        // 初始化屏幕宽度
        displayWidth = metric.widthPixels;
        // 初始化屏幕高度
        displayHeight = metric.heightPixels;
    }
    private static Handler sHandler;


    public void hideNavigationBar() {
        sHandler = new Handler();

        sHandler.post(mHideRunnable); // hide the navigation bar

        final View decorView = getWindow().getDecorView();
        decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                sHandler.post(mHideRunnable); // hide the navigation bar
            }
        });
    }

    Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            int flags;
            int curApiVersion = android.os.Build.VERSION.SDK_INT;
            // This work only for android 4.4+
            if (curApiVersion >= Build.VERSION_CODES.KITKAT) {
                // This work only for android 4.4+
                // hide navigation bar permanently in android activity
                // touch the screen, the navigation bar will not show
                flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_IMMERSIVE
                        | View.SYSTEM_UI_FLAG_FULLSCREEN;

            } else {
                // touch the screen, the navigation bar will show
                flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            }

            // must be executed in main thread :)
            getWindow().getDecorView().setSystemUiVisibility(flags);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initThemeColor();
//        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.home_main);
//        hideNavigationBar();//虚拟返回键问题
//        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        initMetrics();
        homeMainActionsListener = DaggerHomeMainContractComponent
                .builder()
                .appComponent(CkzApplication.getAppComponent())
                .homeMainPresenterModule(new HomeMainPresenterModule(this))
                .build().getHomeMainPresenter();
        initTabView();
        initFragment();
        initFragmentCommit();
        // 初始化SlideMenu
        initRightMenu();
        //接收
        rxSubscription = RxBus
                .getDefault()
                .toObservable(PostTypeData.class)
                .subscribe(new Action1<PostTypeData>() {
                    @Override
                    public void call(PostTypeData post) {
                        //操作侧滑
                        if (post.getType() == 0 && post.getTypes() == null && post.isPullDown() == true) {
                            KLog.i("Evd", "打开侧滑");
                            getSlidingMenu().showSecondaryMenu();
                        }
                        if (post.getType() == 1 && post.getTypes() == null && post.isPullDown() == true) {
                            KLog.i("Evd", "关闭侧滑");
                            slidingMenu.showContent();
                            slidingMenu.isMenuShowing();
                        }
                        //刷新右边数据
                        if (post.getType() == 1 && post.getTypes() != null && post.isPullDown() == true) {
                            KLog.i("Evd", "刷新数据");
                            homeRightFragment.updateUi(post.getTypes());
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        KLog.i("TAG", "call - throwable");
                    }
                });

        String version_code = (String) SPUtil.get(this, "version_code", "1");
        String version_name = (String) SPUtil.get(this, "version_name", "1.0.0");
        /**
         * @see HomeMainPresenter#isDownloadApk(String, String)
         */
        homeMainActionsListener.isDownloadApk(version_code, version_name, false);

    }

    @Override
    protected void onPause() {
        super.onPause();

    }





    public void initFragment() {
        homeIndexFragment = new HomeIndexFragment();
        homeAccountingFragment = HomeAccountingFragment.newInstance(new Bundle());
        homeMeFragment = new HomeMeFragment();

    }

    public void initFragmentCommit() {
        fragments = new Fragment[]{homeIndexFragment, homeAccountingFragment, homeMeFragment};
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, homeIndexFragment).show(homeIndexFragment).commit();
    }


    public void initTabView() {
        aa = this.getResources().getDrawable(R.mipmap.ic_home_share_selected);
        bb = this.getResources().getDrawable(R.mipmap.ic_home_money_selected);
        cc = this.getResources().getDrawable(R.mipmap.ic_home_me_selected);

        a = this.getResources().getDrawable(R.mipmap.ic_home_share_unselected);
        b = this.getResources().getDrawable(R.mipmap.ic_home_money_unselected);
        c = this.getResources().getDrawable(R.mipmap.ic_home_me_unselected);
        btnCommunication.setCompoundDrawablesWithIntrinsicBounds(null, aa, null, null);
        mTabs = new Button[3];
        mTabs[0] = btnCommunication;
        mTabs[1] = btnClientManagement;
        mTabs[2] = btnMarketingCommunication;
        mTabs[0].setSelected(true);
        registerForContextMenu(mTabs[1]);
    }

    public void onTabClicked(View v) {
        boolean is_login = (boolean) SPUtil.get(this, "is_login", false);

        if (v.getId() != R.id.btn_communication && !is_login) {
            EasyToast.showShort(this, "你还未登录哦,请先登录");
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }


        switch (v.getId()) {
            case R.id.btn_communication:
                index = 0;
                slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
                btnCommunication.setCompoundDrawablesWithIntrinsicBounds(null, aa, null, null);
                btnClientManagement.setCompoundDrawablesWithIntrinsicBounds(null, b, null, null);
                btnMarketingCommunication.setCompoundDrawablesWithIntrinsicBounds(null, c, null, null);
                break;
            case R.id.btn_client_management:
                slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
                btnCommunication.setCompoundDrawablesWithIntrinsicBounds(null, a, null, null);
                btnClientManagement.setCompoundDrawablesWithIntrinsicBounds(null, bb, null, null);
                btnMarketingCommunication.setCompoundDrawablesWithIntrinsicBounds(null, c, null, null);
                index = 1;
                break;
            case R.id.btn_marketing_communication:

                slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
                btnCommunication.setCompoundDrawablesWithIntrinsicBounds(null, a, null, null);
                btnClientManagement.setCompoundDrawablesWithIntrinsicBounds(null, b, null, null);
                btnMarketingCommunication.setCompoundDrawablesWithIntrinsicBounds(null, cc, null, null);
                index = 2;
                break;
        }
        if (currentTabIndex != index) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            trx.hide(fragments[currentTabIndex]);//隐藏当前
            if (!fragments[index].isAdded()) {
                trx.add(R.id.fragment_container, fragments[index]);
            }
            trx.show(fragments[index]).commit();
        }
        mTabs[currentTabIndex].setSelected(false);
        // 把当前tab设为选中状态
        mTabs[index].setSelected(true);
        currentTabIndex = index;//记录本次选中的
    }

    private void initRightMenu() {
//		Fragment leftMenuFragment = new MenuLeftFragment();
        homeRightFragment = new HomeRightFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.id_right_menu_frame, homeRightFragment).commit();
        setBehindContentView(R.layout.left_menu_frame);
//		getSupportFragmentManager().beginTransaction()
//				.replace(R.id.id_left_menu_frame, rightMenuFragment).commit();
        slidingMenu = getSlidingMenu();
        slidingMenu.setMode(SlidingMenu.RIGHT);
        // 设置触摸屏幕的模式
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
        slidingMenu.setShadowDrawable(R.drawable.shadow);
        // 设置滑动菜单视图的宽度
        slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
//		menu.setBehindWidth()
        // 设置渐入渐出效果的值
        slidingMenu.setFadeDegree(0.35f);
//        slidingMenu.setBehindScrollScale(1.0f);
        slidingMenu.setSecondaryShadowDrawable(R.drawable.shadow);
        //设置右边（二级）侧滑菜单
        slidingMenu.setSecondaryMenu(R.layout.right_menu_frame);

    }

    private long exitTime = 0;

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            EasyToast.showShort(this, "再按一次,退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            AppManager.getAppManager().finishAllActivity();
        }
    }
}
